package register.pojo.dao.impl;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import register.pojo.User;
import register.pojo.dao.UserDao;
import utill.DBUtil;

public class UserDaoImpl implements UserDao {

	private Connection connection=DBUtil.createConnection();
	@Override
	public int add(User user) {
		// TODO Auto-generated method stub
		String sqlString="insert into users(uname,sal,sex,birth,uhead) values(?,?,?,?,?)";
		int m=0;
		PreparedStatement pst ;
		try {
			pst=connection.prepareStatement(sqlString);
			pst.setString(1,new String( user.getName().getBytes(),"UTF-8"));
			pst.setDouble(2, user.getSal());
			pst.setString(3, user.getSex());
			pst.setDate(4, new java.sql.Date( user.getBirth().getTime()));
			pst.setBytes(5, user.getHead());
			m=pst.executeUpdate();
			DBUtil.close(pst, null);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return m;
	}

	@Override
	public List<User> findAll() {
		// TODO Auto-generated method stub
		List<User> list =new ArrayList<User>();
		PreparedStatement pst=null;
		ResultSet rSet=null;
		String sql="select * from users";
		try {
			pst=connection.prepareStatement(sql);
			rSet=pst.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			while(rSet.next())
			{
				User tempUser=new User();
				tempUser.setName(rSet.getString("uname"));
				tempUser.setSal(rSet.getDouble("sal"));
				tempUser.setSex(rSet.getString("sex"));
				tempUser.setBirth(rSet.getDate("birth"));
				tempUser.setHead(rSet.getBytes("uhead"));
				list.add(tempUser);
			} 
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DBUtil.close(pst, rSet);
		return list;
	}

	public void closeConnect  () {
		try {
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
